﻿using Microsoft.Extensions.Options;
using PlayingCards.Comm.Extensions;
using PlayingCards.Model.Conf;
using PlayingCards.Model.Entity;
using PlayingCards.Model.Result;
using PlayingCards.Repository.BaseRepository;
using PlayingCards.Service.IEntityService;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PlayingCards.Service.EntityService
{
    public class UserService : IUserService
    {
        public BaseRepository<Player> _player;
        private JWTToken _tokenModel = null;
        public UserService(BaseRepository<Player> player , IOptions<JWTToken> options) 
        {
            _player = player;
            _tokenModel = options.Value;
        }
        public async Task<Result<string>> Login(string openid)
        {
            var user = _player.GetSingle(e => e.OpenId == openid);
            if(user == null)
            {
                _player.Insert(new Player
                {
                    PlayerNumber = "P" + DateTimeExtension.GenerateNumberString(),
                    NickName = StringExtension.GetRandomString(),
                    OpenId = openid,
                });
            }
            var token = StringExtension.GetJwtToken(openid, new JWTToken
            {
                SecurityKey = _tokenModel.SecurityKey,
                Issuer = _tokenModel.Issuer,
                Audience = _tokenModel.Audience,
                ExpiresTime = _tokenModel.ExpiresTime
            });
            return new Result<string> { Data = token };
        }
    }
}
